#!/bin/bash
#sh ./get_all_merger_branch_names.sh -currentBranch "${currentBranch}" -rebaseFrom "${currentBranchRebaseFrom}"
:<<!
获取本分支的rebase日期和该日期后的所有合入分支名
!
#responseResult=$(git log --graph --pretty=format:'%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --after "10-12-2022" --merges )
#responseResult=$(git log --pretty=format:'%s %Cgreen(%cd) %C(bold blue)<%an>%Creset' --after "10-12-2022" --merges)

#responseResult=$(git log --pretty=format:'%C(yellow)%H' --after "10-12-2022" --no-merges )

#git log --pretty=format:'-%C(yellow)%d%Creset %s' --after "2022-10-16"


JQ_EXEC=`which jq`


# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}/..
CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute%/*} # 使用此方法可以避免路径上有..
# CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}
# echo "CommonFun_HomeDir_Absolute=${CommonFun_HomeDir_Absolute} ✅"

qscript_path_get_filepath="${CommonFun_HomeDir_Absolute}/qscript_path_get.sh"
rebasebranch_last_commit_date_script_path="$(sh ${qscript_path_get_filepath} qbase rebasebranch_last_commit_date)"
calculate_newdate_script_path="$(sh ${qscript_path_get_filepath} qbase calculate_newdate)"


CommonScriptResultJSONFilePath="${CommonFun_HomeDir_Absolute}/json/common_script_result.json"
Update_code_message_SCRIPT_PATH="${CommonFun_HomeDir_Absolute}/base/error_code_message/update_code_message.sh"

# exit

exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}


# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'


function debug_log() {
    if [ "${isRelease}" == true ]; then
        echo "$1"
    fi
}

while [ -n "$1" ]
do
    case "$1" in
        -currentBranch|--current-branch) currentBranch=$2; shift 2;;
        -rebaseFrom|--currentBranch-rebaseFrom) currentBranchRebaseFrom=$2; shift 2;;   # "origin/development"
        --) break ;;
        *) break ;;
    esac
done
#currentBranch=${currentBranch##*/} # 取最后的component
#echo "currentBranch=${currentBranch}"

if [ -z "${currentBranch}" ] || [ -z "${currentBranchRebaseFrom}" ]; then
    echo "❌Error:缺少参数，请检查是否设置 -currentBranch 和 -rebaseFrom"
    exit 1
fi



debug_log "${YELLOW}正在执行命令(获取要搜索的起始期间):《 ${BLUE}sh ${rebasebranch_last_commit_date_script_path} -rebaseBranch \"${currentBranchRebaseFrom}\" ${YELLOW}》${NC}"
branchLastCommitDateResult=$(sh ${rebasebranch_last_commit_date_script_path} -rebaseBranch "${currentBranchRebaseFrom}")
if [ $? != 0 ]; then
    exit_script
fi
lastCommmitDateForDevelopmentResult=${branchLastCommitDateResult}
#lastCommmitDateForDevelopmentResult="2022-10-17 18:07:33"
debug_log "${GREEN}${BLUE}${currentBranchRebaseFrom} ${GREEN}分支最后一条记录的提交时间 lastCommmitDateForDevelopment= ${BLUE}${lastCommmitDateForDevelopmentResult}${NC}"


searchFromDateString=$(sh ${calculate_newdate_script_path} --old-date "${lastCommmitDateForDevelopmentResult}" --add-value "1")
if [ $? != 0 ]; then
    echo "❌Error: 执行出错《 sh ${calculate_newdate_script_path} --old-date \"${lastCommmitDateForDevelopmentResult}\" --add-value \"1\" 》"
    exit_script
fi
debug_log "所以，搜索的开始时间searchFromDateString= ${BLUE}${searchFromDateString}${NC}"


# 获取本分支在指定日期后的提交记录。用来判断rebase的时间后，如果没有新的提交，则你的打包将只需打包现有的功能
function getNewCommitAfterDate() {
    searchFromDateString=$1
    
    debug_log "首先执行命令(获取本分支在指定日期后的提交记录)：《 git log --pretty=format:'%C(yellow)%H' --after \"${searchFromDateString}\" 》"
    allCommitsAfterDateResponseResult=$(git log --pretty=format:'%C(yellow)%H' --after "${searchFromDateString}") # 注意:此处只能打印hash值，不添加%s去打印commit信息，才能避免下面因为有些commit信息有空格或换行，从而导致无法规律性的分断数组，从而找不到最后一条
}

function getFirstCommitSourceBranchNameAfterDate() {
    searchFromDateString=$1
    
    #echo "------下面开始获取本分支在${searchFromDateString}后第一条提交记录的根源分支名------"
    debug_log "${YELLOW}正在执行命令(获取本分支在指定日期后第一条提交记录的根源分支名)：《 ${BLUE}sh ${CurrentDIR_Script_Absolute}/get_fist_commit_source_branch_after_date.sh  -date \"${searchFromDateString}\" --useBySource \"yes\" --currentBranch \"${currentBranch}\" ${YELLOW}》${NC}"
    sourceBranchForFisrtCommit=$(sh ${CurrentDIR_Script_Absolute}/get_fist_commit_source_branch_after_date.sh  -date "${searchFromDateString}" --useBySource "yes" --currentBranch "${currentBranch}")
    if [ $? != 0 ]; then
        return 1
    fi

    if [ -z "${sourceBranchForFisrtCommit}" ] || [ "${sourceBranchForFisrtCommit}" == 1 ]; then
        echo "============友情提示🤝🤝🤝：未找到${currentBranch}本分支在${searchFromDateString}后第一条提交记录的根源分支名，所以你的打包将只打包现有的功能"
    else
        debug_log "${GREEN}恭喜:获得本分支在指定日期后第一条提交记录的根源分支名 sourceBranchForFisrtCommit=${BLUE}${sourceBranchForFisrtCommit}${NC}"
    fi
}

# 获取本分支在指定时间后,新提交属于的所有分支名，以之后提供给测试人员测试信息
function getNewCommitSourceBranchNames() {
    debug_log "✅✅✅✅✅ 进入测试 $FUNCNAME"
    debug_log "------下面开始整理本分支在${searchFromDateString}后新提交所包含的所有功能分支名(自动去重)------"
    searchFromDateString=$1
    
    getNewCommitAfterDate "${searchFromDateString}"
    if [ ${#allCommitsAfterDateResponseResult} == 0 ]; then
        debug_log "============🤝🤝🤝结果如下：经[$FUNCNAME]方法得本分支[${currentBranch}]在${searchFromDateString}后没有任何的提交记录，所以你的打包将只打包现有的功能，且不用也没有再去获取新合入的分支信息"
        return 0
    fi

    # 加入根源分支
    getFirstCommitSourceBranchNameAfterDate "${searchFromDateString}"
    if [ $? != 0 ]; then
        echo "${sourceBranchForFisrtCommit}" # 此时值为出错原因
        return 1
    fi
    newCommitSourceBranchNamesResult[${#newCommitSourceBranchNamesResult[*]}]=${sourceBranchForFisrtCommit}

    # 加入新合入的其他分支
    warningMergeBranchName=("dev_publish_in")
    debug_log "${YELLOW}正在执行脚本文件(获取指定日期之后的所有合入记录(已去除 HEAD -> 等))：《 ${BLUE}sh ${CurrentDIR_Script_Absolute}/get_merger_recods_after_date.sh --searchFromDateString \"${searchFromDateString}\" --currentBranch \"${currentBranch}\" --warningMergeBranchName \"${warningMergeBranchName[*]}\" ${YELLOW}》${NC}"
    matchMergeBranchNameJson=$(sh ${CurrentDIR_Script_Absolute}/get_merger_recods_after_date.sh --searchFromDateString "${searchFromDateString}" --currentBranch "${currentBranch}" --warningMergeBranchName "${warningMergeBranchName[*]}")
    if [ $? != 0 ]; then
        PackageErrorCode=1
        PackageErrorMessage=$(echo "$matchMergeBranchNameJson" | jq -r '.message')
        echo "正在执行命令(更新可能合入了不该合的分支的信息):《 sh \"${Update_code_message_SCRIPT_PATH}\" -codeMessageJsonF \"${CommonScriptResultJSONFilePath}\" -code \"${PackageErrorCode}\" -message \"${PackageErrorMessage}\" 》"
        sh "${Update_code_message_SCRIPT_PATH}" -codeMessageJsonF "${CommonScriptResultJSONFilePath}" -code "${PackageErrorCode}" -message "${PackageErrorMessage}"
        if [ $? != 0 ]; then
            echo "❌Error:更新 package_code:${PackageErrorCode} 和 package_message:${PackageErrorMessage} 失败"
            return 1
        fi
        # sh "${qbase_update_json_file_singleString_script_path}" -jsonF "${CommonScriptResultJSONFilePath}" -k 'package_code' -v "${PackageErrorCode}"
        # if [ $? != 0 ]; then
        #     echo "❌Error:更新 package_code:${PackageErrorCode} 失败"
        #     exit 1
        # fi
        # sh "${qbase_update_json_file_singleString_script_path}" -jsonF "${CommonScriptResultJSONFilePath}" -k 'package_message' -v "${PackageErrorMessage}"
        # if [ $? != 0 ]; then
        #     echo "❌Error:更新 package_message:${PackageErrorMessage} 失败"
        #     exit 1
        # fi

        return 1
    fi

    # echo "======================================$matchMergeBranchNameJson======================================"
    # echo "======================================$newCommitSourceBranchNamesResult======================================"
    
    matchMergeBranchNames=$(echo "$matchMergeBranchNameJson" | jq -r '.data')
    matchMergeBranchNames=(${matchMergeBranchNames})
    if [ -n "${matchMergeBranchNames}" ]; then
        matchMergeBranchNameCount=${#matchMergeBranchNames[@]}
        for ((i=0;i<matchMergeBranchNameCount;i++))
        do
            devBranchName=${matchMergeBranchNames[i]}
            newCommitSourceBranchNamesResult[${#newCommitSourceBranchNamesResult[*]}]=${devBranchName}
        done
    fi

    #[shell 数组去重](https://www.jianshu.com/p/1043e40c0502)
    newCommitSourceBranchNamesResult=($(awk -v RS=' ' '!a[$1]++' <<< ${newCommitSourceBranchNamesResult[@]}))
    debug_log "${GREEN}============🤝🤝🤝整合分支根源+合入其的其他分支结果如下(去重后)：得分支 ${BLUE}[${currentBranch}] ${GREEN}在 ${BLUE}${searchFromDateString} ${GREEN}后有 ${BLUE}${#newCommitSourceBranchNamesResult[@]} ${GREEN}个分支合入，分别为newCommitSourceBranchNamesResult= ${BLUE}${newCommitSourceBranchNamesResult[*]}${GREEN}============${NC}"
}






# 获取本分支在rebase指定分支后所包含的所有分支名(自己+合入)的值
function getAllContainBranchNames() {
    debug_log "正在执行命令(获取本分支在指定时间后,新提交属于的所有分支名)：《 getNewCommitSourceBranchNames \"${searchFromDateString}\"》"
    getNewCommitSourceBranchNames "${searchFromDateString}"
    if [ $? != 0 ]; then
        PackageErrorCode=-1
        PackageErrorMessage="获取所有打包的分支名执行失败了"
        sh "${Update_code_message_SCRIPT_PATH}" -codeMessageJsonF "${CommonScriptResultJSONFilePath}" -code "${PackageErrorCode}" -message "${PackageErrorMessage}"
        if [ $? != 0 ]; then
            echo "❌Error:更新 package_code:${PackageErrorCode} 和 package_message:${PackageErrorMessage} 失败"
            return 1
        fi

        return 1
    fi

    debug_log "开始整合最后的分支总值(本分支+合入的分支[${#newCommitSourceBranchNamesResult[@]}个])"
    allContainBranchNamesResult=()
    allContainBranchNamesResult[${#allContainBranchNamesResult[*]}]=${currentBranch}
    if [ ${#newCommitSourceBranchNamesResult[@]} -gt 0 ]; then
        newCommitSourceBranchNameCount=${#newCommitSourceBranchNamesResult[@]}
        for ((i=0;i<newCommitSourceBranchNameCount;i++))
        do
            devBranchName=${newCommitSourceBranchNamesResult[i]}
            allContainBranchNamesResult[${#allContainBranchNamesResult[*]}]=${devBranchName}
        done
    fi
    debug_log "============ 🤝🤝🤝整合本分支+合入的分支结果如下(去重前)：本分支[${currentBranch}]在rebase[${REBASE_BRANCH}]分支后所包含的所有分支名(自己+合入)的值有${#allContainBranchNamesResult[@]}个，分别为allContainBranchNamesResult=${allContainBranchNamesResult[*]}"
    #[shell 数组去重](https://www.jianshu.com/p/1043e40c0502)
    allContainBranchNamesResult=($(awk -v RS=' ' '!a[$1]++' <<< ${allContainBranchNamesResult[@]}))
    

    debug_log "${GREEN}============ 恭喜:🤝🤝🤝整合本分支+合入的分支结果如下(去重后)：本分支 ${BLUE}[${currentBranch}] ${GREEN}在 rebase[${REBASE_BRANCH}] ${GREEN}分支后所包含的所有分支名(自己+合入)的值有 ${BLUE}${#allContainBranchNamesResult[@]} ${GREEN}个，分别为 ${BLUE}allContainBranchNamesResult= ${BLUE}${allContainBranchNamesResult[*]}${NC}"
}


getAllContainBranchNames
if [ $? != 0 ]; then
    exit_script
fi

# 输出结果给外部
echo '{"searchFromDateString":"'"$searchFromDateString"'","data":"'"${allContainBranchNamesResult[*]}"'"}'


# 取值示例
# allContainBranchNamesJsonResult=$(sh ${CurrentDIR_Script_Absolute}/get_all_merger_branch_names.sh -currentBranch "${currentBranch}" -rebaseFrom "${currentBranchRebaseFrom}")
# allContainBranchNamesResult=$(echo "$allContainBranchNamesJsonResult" | jq -r '.data')